package apptoko.com;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import apptoko.com.fragment.CategoryFragment;
import apptoko.com.fragment.HomeListFragment;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import apptoko.com.R;
import com.astuetz.viewpager.extensions.PagerSlidingTabStrip;
import com.google.analytics.tracking.android.EasyTracker;

public class HomeStoreActivity extends SherlockFragmentActivity implements OnItemSelectedListener {
	
	private String store;
	private ViewPager viewPager;
	private Resources res;
	private HomeFragmentAdapter adapter;
	private View listNav;
	private Spinner spinner;
	private int selectedPosition = 0;
	private int indicatorColor;
	private String language="";
	private String countryCode;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		store = getIntent().getStringExtra(Constants.STORE_KEY);
		if(store == null){
			store = "apps";
		}
//		if(store.equalsIgnoreCase("apps")){
			setTheme(R.style.Theme_Styled_Home);
			setThemeLowEndDevice(R.drawable.action_bar_home);
			indicatorColor = R.color.app_indicator;
//		} else if(store.equalsIgnoreCase("books")){
//			setTheme(R.style.Theme_Styled_Book);
//			setThemeLowEndDevice(R.drawable.action_bar_book);
//			indicatorColor = R.color.ebook_indicator;
//		} else if(store.equalsIgnoreCase("comics")){
//			setTheme(R.style.Theme_Styled_Comic);
//			setThemeLowEndDevice(R.drawable.action_bar_comic);
//			indicatorColor = R.color.comic_indicator;
//		} else if(store.equalsIgnoreCase("movies")){
//			setTheme(R.style.Theme_Styled_Movie);
//			setThemeLowEndDevice(R.drawable.action_bar_movie);
//			indicatorColor = R.color.film_indicator;
//		} else if(store.equalsIgnoreCase("games")){
//			setTheme(R.style.Theme_Styled_Apps);
//			setThemeLowEndDevice(R.drawable.action_bar_apps);
//			indicatorColor = R.color.app_indicator;
//		} else if(store.equalsIgnoreCase("gift")){
//			setTheme(R.style.Theme_Styled_Gift);
//			setThemeLowEndDevice(R.drawable.action_bar_gift);
//			indicatorColor = R.color.gift_indicator;
//		}
		super.onCreate(arg0);
		setContentView(R.layout.list_pager);
		countryCode = Utils.getStaticCountryCode(this);
		EasyTracker.getInstance().setContext(this);
		selectedPosition = getIntent().getIntExtra(Constants.NAV_POSITION, 0);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        listNav = getLayoutInflater().inflate(R.layout.list_navigation, null);
        spinner = (Spinner) listNav.findViewById(R.id.spn_list_nav);
        spinner.setSelection(selectedPosition);
        spinner.setOnItemSelectedListener(this);
        viewPager = (ViewPager) findViewById(R.id.pager);
        getSupportActionBar().setCustomView(listNav);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        language= UILApplication.getInstance().getConfig().locale.getLanguage();
        initView();
	}
	
	private void initView() {
		// TODO Auto-generated method stub
		res = getResources();
        
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int pageMargin = metrics.widthPixels / 48;
        
		adapter = new HomeFragmentAdapter(getSupportFragmentManager());
		viewPager.setOffscreenPageLimit(6);
		viewPager.setPageMargin(pageMargin);
		viewPager.setPageMarginDrawable(R.drawable.bg_pagemargin_xml);
		viewPager.setAdapter(adapter);
//		viewPager.setCurrentItem(1);
		PagerSlidingTabStrip indicator = (PagerSlidingTabStrip) findViewById(R.id.indicator);
        indicator.setViewPager(viewPager);
        indicator.setIndicatorColorResource(indicatorColor);
        int pixelSize = (int) (14 * metrics.scaledDensity); 
        indicator.setTextSize(pixelSize);
	}

	private void setThemeLowEndDevice(int drawableId){
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(drawableId);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
	}
	
	@SuppressLint("NewApi")
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if(language.equals(UILApplication.getInstance().getConfig().locale.getLanguage())){
			super.onResume();
			invalidateOptionsMenu();
		}else{
			super.onResume();
			initView();
			invalidateOptionsMenu();
			language= UILApplication.getInstance().getConfig().locale.getLanguage();
		}
		
	}
	

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.activity_home, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.menu_search:
			Intent search = new Intent(this, SearchActivity.class);
			search.putExtra(Constants.SEARCH_TYPE, store);
			startActivity(search);
			return true;
		case R.id.menu_account:
			boolean isLogin = Utils.getStaticIsLogin(this);
			if(isLogin){
				Intent account = new Intent(this, AccountActivity.class);
				startActivity(account);
			} else {
				Intent login = new Intent(this, LoginActivity.class);
				startActivity(login);
			}
			return true;
		case R.id.menu_manage:
			if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games")){
				Intent i = new Intent(this, AppManageActivity.class);
				i.putExtra(Constants.STORE_KEY, store);
				startActivity(i);
			} else if(store.equalsIgnoreCase("books") || store.equalsIgnoreCase("comics")){
				Intent i = new Intent(this, BookManageActivity.class);
				i.putExtra(Constants.STORE_KEY, store);
				startActivity(i);
			} else {
				Intent i = new Intent(this, MoviesManageActivity.class);
				i.putExtra(Constants.STORE_KEY, store);
				startActivity(i);
			}
			return true;
		case R.id.menu_setting:
			Intent setting = new Intent(this, SettingsActivity.class);
			startActivity(setting);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class HomeFragmentAdapter extends FragmentStatePagerAdapter {

		protected String[] TITLE;// 

		public HomeFragmentAdapter(FragmentManager fm) {
			super(fm);
			if(countryCode.equalsIgnoreCase("vn")){
				TITLE = new String[] { res.getString(R.string.category), res.getString(R.string.hot_app), res.getString(R.string.top_new), res.getString(R.string.top_download)};
				//TITLE = new String[] { res.getString(R.string.category).toUpperCase(Locale.US), res.getString(R.string.featured).toUpperCase(Locale.US), res.getString(R.string.hot_app).toUpperCase(Locale.US), res.getString(R.string.top_new).toUpperCase(Locale.US), res.getString(R.string.top_download).toUpperCase(Locale.US)};
			} else {
				TITLE = new String[] { res.getString(R.string.category), res.getString(R.string.hot_app), res.getString(R.string.top_new), res.getString(R.string.top_download)};
			}
		}

		@Override
		public Fragment getItem(int position) {
			if(countryCode.equalsIgnoreCase("vn")){
				if(position == 0){
					CategoryFragment catFrag = new CategoryFragment();
					Bundle b = new Bundle();
					b.putString(Constants.STORE_KEY, store);
					catFrag.setArguments(b);
					return catFrag;
				} else //if(position == 1)
				{
//					HomeMetroFragment fragment = HomeMetroFragment.newInstance(TITLE[1]);
//					Bundle bundle = new Bundle();
//					bundle.putString(HomeMetroFragment.PAGE, store);
//					bundle.putString(Constants.STORE_KEY, store);
//					fragment.setArguments(bundle);
//					return fragment;
					HomeListFragment listFragment = new HomeListFragment();
					Bundle bundle = new Bundle();
					bundle.putString(Constants.TOP, TITLE[position]);
					bundle.putString(Constants.STORE_KEY, store);
					listFragment.setArguments(bundle);
					return listFragment;
				}
//				else {
//					HomeListFragment listFragment = new HomeListFragment();
//					Bundle bundle = new Bundle();
//					bundle.putString(Constants.TOP, TITLE[position]);
//					bundle.putString(Constants.STORE_KEY, store);
//					listFragment.setArguments(bundle);
//					return listFragment;
//				}
			} else {
				if(position == 0){
					CategoryFragment catFrag = new CategoryFragment();
					Bundle b = new Bundle();
					b.putString(Constants.STORE_KEY, store);
					catFrag.setArguments(b);
					return catFrag;
				} else {
					HomeListFragment listFragment = new HomeListFragment();
					Bundle bundle = new Bundle();
					bundle.putString(Constants.TOP, TITLE[position]);
					bundle.putString(Constants.STORE_KEY, store);
					listFragment.setArguments(bundle);
					return listFragment;
				}
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return TITLE.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			// TODO Auto-generated method stub
			return TITLE[position];
		}
		
		@Override
		public void setPrimaryItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			if(position > 0){
				HomeListFragment frag = (HomeListFragment) object;
				frag.init();
			}
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (pos) {
		case 0:
			if(selectedPosition != 0){
				intent = new Intent(this, HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "apps");
				intent.putExtra(Constants.NAV_POSITION, 0);
				startActivity(intent);
				finish();
			}
			break;
		case 1:
			if(selectedPosition != 1){
				intent = new Intent(this, HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "games");
				intent.putExtra(Constants.NAV_POSITION, 1);
				startActivity(intent);
				finish();
			}
			break;
//		case 2:
//			if(selectedPosition != 2){
//				intent = new Intent(this, HomeStoreActivity.class);
//				intent.putExtra(Constants.STORE_KEY, "books");
//				intent.putExtra(Constants.NAV_POSITION, 2);
//				startActivity(intent);
//				finish();
//			}
//			break;
//		case 3:
//			if(selectedPosition != 3){
//				intent = new Intent(this, HomeStoreActivity.class);
//				intent.putExtra(Constants.STORE_KEY, "comics");
//				intent.putExtra(Constants.NAV_POSITION, 3);
//				startActivity(intent);
//				finish();
//			}
//			break;
//		case 4:
//			if(selectedPosition != 4){
//				intent = new Intent(this, HomeStoreActivity.class);
//				intent.putExtra(Constants.STORE_KEY, "movies");
//				intent.putExtra(Constants.NAV_POSITION, 4);
//				startActivity(intent);
//				finish();
//			}
//			break;
//		case 5:
//			if(selectedPosition != 5){
//				intent = new Intent(this, GiftsActivity.class);
//				startActivity(intent);
//				spinner.setSelection(selectedPosition);
//			}
//			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.findItem(R.id.menu_account)
		.setTitle(getResources().getString(R.string.account));
		menu.findItem(R.id.menu_manage)
		.setTitle(getResources().getString(R.string.manage));
		menu.findItem(R.id.menu_setting)
		.setTitle(getResources().getString(R.string.setting));
		
		return true;
	}
}
